<template>
    <el-dialog v-model="state.isShowDialog" width="796px">
    <el-form-item label="菜单权限" v-loading="state.loading">
        <el-tree
            ref="treeRef"
            :data="state.menuData"
            node-key="id"
            show-checkbox
            :props="{ children: 'children', label:'title',class: treeNodeClass }"
            icon="ele-Menu"
            highlight-current
            default-expand-all
        />     
	</el-form-item>
    <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog" size="default">{{$t('message.userOperation.cancel')}}</el-button>
                <el-button type="primary" @click="submit" size="default">{{$t('message.userOperation.submit')}}</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { reactive,ref} from 'vue';
import { ElMessage, ElTree } from 'element-plus';
import { SysMenu } from '/@/api-services/models/system';
import { feature } from "/@/utils/axios-utils";
import roleApi from '/@/api-services/apis/system/roleApi';
import menuApi from '/@/api-services/apis/system/menuApi';
const treeRef = ref<InstanceType<typeof ElTree>>();
const state = reactive({
    loading:false,
    isShowDialog: false,
    title: '',
    roleId:0,
    menuData: [] as Array<SysMenu>, // 菜单数据
    checkedMenu:[] as Array<number>
});

const openDialog=async(row:any)=>{
    state.isShowDialog=true;
    state.roleId=row.id;
    state.checkedMenu=[];
    //查询角色已授权菜单
    var ownMenu = await roleApi.getOwnMenu({id:row.id});
    //查询当前用户授权菜单
    var menuTree=await menuApi.getMenuTree();
    state.menuData=menuTree.data.data??[];
    setTimeout(() => {
        findFunc(state.menuData,ownMenu.data.data);      
        treeRef.value?.setCheckedKeys(state.checkedMenu);
	}, 100);
}

//处理已授权菜单数据
const findFunc=(menuData:any,ownMenu:any)=>{
    if(ownMenu.length==0)return;
    menuData?.forEach((it:any)=>{
        if(it.children.length==0){
            if(ownMenu.findIndex((id: any) => it.id === id)>-1){
                state.checkedMenu.push(it.id)
            }
        }        
        else {
            //只需要记录最后一层id，父级会自动check
            for(let i=0;i<it.children.length;i++){
                if(it.children[i].children.length>0){
                    findFunc(it.children,ownMenu)
                }
                else{
                    if(ownMenu.findIndex((id: any) =>it.children[i].id===id)>-1){
                        state.checkedMenu.push(it.children[i].id)
                    }
                }
            }
        }        
    })
}

// 叶子节点同行显示样式
const treeNodeClass = (node: SysMenu) => {
	let addClass = true; // 添加叶子节点同行显示样式
	for (const key in node.children) {
		// 如果存在子节点非叶子节点，不添加样式
		if (node.children[key].children?.length ?? 0 > 0) {
			addClass = false;
			break;
		}
	}
	return addClass ? 'penultimate-node' : '';
};

const closeDialog=()=>{
    state.isShowDialog=false;
};
const submit=async()=>{
    var menuIdList = treeRef.value?.getCheckedKeys() as Array<number>;
    var half=treeRef.value?.getHalfCheckedKeys()as Array<number>;
    menuIdList=menuIdList.concat(half);
    const [err]=await feature(roleApi.grantRoleMenus({id:state.roleId,menuList:menuIdList}))
    if(err){
        ElMessage.error(err.message)
    }
    else{
        closeDialog()
    }
};

// 导出对象
defineExpose({ openDialog });
</script>

<style lang="scss" scoped>
.menu-data-tree {
	width: 100%;
	border: 1px solid var(--el-border-color);
	border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
	padding: 5px;
}

:deep(.penultimate-node) {
	.el-tree-node__children {
		padding-left: 40px;
		white-space: pre-wrap;
		line-height: 100%;

		.el-tree-node {
			display: inline-block;
		}

		.el-tree-node__content {
			padding-left: 5px !important;
			padding-right: 5px;

			// .el-tree-node__expand-icon {
			// 	display: none;
			// }
		}
	}
}
</style>
